package util
{
	import flash.utils.ByteArray;

	public class BytesUtil
	{
		
		public static function readS24(bytes:ByteArray):int
		{
			var b:int = bytes.readUnsignedByte();
			b |= bytes.readUnsignedByte()<<8;
			b |= bytes.readByte()<<16;
			return b;
		}
		
		/**u30,u32,s32的变量长度编码根据编码规模不同会消耗1到5个字节。每个字节的前7位用于存储值，如果第八位也被使用了，那么abcfile的下一个字节也是值的一部分。*/
		public static function readU16(bytes:ByteArray):int
		{
			var b:int = readBytes8ToInt(bytes);
			b &= 0x000000FF;//只保留低8位
			var u32:int = b;
			b = readBytes8ToInt(bytes);
			b &= 0xFF;
			u32 = u32 & 0x0000007f | b << 7;
			return u32;
		}
		
		
		public static function readU30(bytes:ByteArray):int
		{
			var length:int = readU32(bytes);
			return (int)(length & 0x3FFFFFFF );
		}
		
		public static function readS32(bytes:ByteArray):int
		{
			var result:int = readU32(bytes);
			if((result & 0x80000000 ) != 0){
				result &= 0x7fffffff;
				result -= 0x80000000;
			}
			return (int)(result);
		}
		
		
		/** 从字节数组中读出一个字节来*/
		public static function readBytes8ToInt(bytes:ByteArray):int
		{
			var ret:int = -1;
			if(bytes.position < bytes.length){
				ret = (bytes.readByte() & 0xff);
			}
			return  ret;
		}
		
		/** 从字节数组中读出4个字节来*/
		public static function readBytes32ToInt(bytes:ByteArray):int
		{
			var ret:int = -1;
			if(bytes.position < bytes.length){
				ret = bytes.readInt();
			}
			return ret;
		}
		
		public static function readU32(bytes:ByteArray):int
		{
			var b:int = readBytes8ToInt(bytes);
			b &= 0x000000FF;//只保留低8位
			var u32:int = b;
			if( !( ( u32 & 0x00000080 ) == 0x00000080 ) ){
				return u32;
			}
			
			b = readBytes8ToInt(bytes);
			b &= 0xFF;
			u32 = u32 & 0x0000007f | b << 7;
			if( !( ( u32 & 0x00004000 ) == 0x00004000 ) ){
				return u32;
			}
			
			b = readBytes8ToInt(bytes);
			b &= 0xFF;
			u32 = u32 & 0x00003fff | b << 14;
			if( !( ( u32 & 0x00200000 ) == 0x00200000 ) ){
				return u32;
			}
			
			b = readBytes8ToInt(bytes);
			b &= 0xFF;
			u32 = u32 & 0x001fffff | b << 21;
			if( !( ( u32 & 0x10000000 ) == 0x10000000 ) ){
				return u32;
			}
			
			b = readBytes8ToInt(bytes);
			b &= 0xFF;
			u32 = u32 & 0x0fffffff | b << 28;
			
			return u32;
		}
		
	}
}